//     抢单池
jQuery(document).ready(
    function () {
        initalTable();
        //控制定制师下拉框
        jQuery.ajax({
            url: '../GrabRequire/GetVbkUserType',
            type: "post",
            data: {},
            success: function (data) {
                userType = data.userType;
                if (data.userType == "VendorAdmin") {
                    //$('.js_filterPlatformUser').show();
                    //定制师一列
                    if (isAll) {
                        $('.js_platformUser').show();
                    } else {
                        $('.js_platformUser').hide();
                    }
                    $(".js_filterNature").hide();
                    $(".js_filterStatus").show();
                    $(".js_progress").hide();
                } else if (data.userType == "AdminPlatformUser") {
                    $(".js_orderStatus").hide();
                    $(".js_filterStatus").hide();
                    $(".js_filterNature").show();
                }
                else {
                    $(".js_filterStatus").show();
                    $(".js_platformUser").hide();
                    $(".js_filterNature").hide();
                    $(".js_progress").hide();
                }
                loadOrderData();
            }
        });

        if (location.pathname.indexOf('NewIndex') > 0) { //新版首页
            jQuery('#head_GrabRequire').parent().addClass("active").siblings().removeClass("active");
            $('.newSorting').click(function () {
                sortName = $(this).attr('data-name');
                sorting = $(this).attr('aria-sort');//ascending descending
                loadOrderData();
            });

        } else {
            jQuery('#head_GrabRequire').attr("class", "Head_href");

        }
        bindEvents();
        //加载提示事件
        $("[data-toggle='tooltip']").tooltip();

        //筛选项样式控制
        $(".js-example-basic-single").select2();
        $("#selectOrderStatus").select2({
            minimumResultsForSearch: -1,
        });
        $("#selectTravelNature").select2({
            minimumResultsForSearch: -1,
        });
    });

var orderType = "GrabOrder";
var isloading = false;
var isAll = false;
var sorting = "ascending";
var sortName = "";
var userType = "";
var pageIndex = 1;
var pageSize = 10;
var isSubmit = false;

/*加载列表页*/
function loadOrderData(type) {
    jQuery("#base_bd").openmask("数据通信请等待....");
    isloading = true;
    if ($(".tooltip") && $(".tooltip") != 'undefined') {
        $(".tooltip").remove();
    }
    var cond = {};
    cond.OrderStatusType = $("#selectOrderStatus").find('option:selected').val();


    var TravelNatureFlag = $("#selectTravelNature").find('option:selected').val();
    if (TravelNatureFlag == 0) {
        cond.TravelNature = "A";
    }
    else if (TravelNatureFlag == 1) {
        cond.TravelNature = "C";
    }
    else if (TravelNatureFlag == 2) {
        cond.TravelNature = "P";
    }
    else
        cond.TravelNature = "A";


    cond.RequireID = $("#filterOrderId").val();
    if (cond.RequireID != '') {
        cond.OrderStatusType = 0;
        cond.TravelNature = "A";
    }
    cond.OrderType = orderType;
    cond.IsAll = isAll;
    cond.SortName = sortName;
    cond.Sorting = sorting;
    cond.Version = 2;
    var condStr = JSON.stringify(cond);
    var sendData = "&pageIndex=" + pageIndex + "&pageSize=" + pageSize + "&condStr=" + condStr;
    sendRequest(baseUrl + "GetRequireList?random=" + getRandom(100), "GET", sendData, function (data) {
            if (data == null || data.Data == null || data.Data.Items == null || data.Data.Items.length == 0) {
                $("#grabOrderList").hide();
                $("#noDataMessage").show();
            } else {
                $("#noDataMessage").hide();
                $("#grabOrderList").show();
            }
            if (cond.RequireID != '') {
                $("#selectOrderStatus option[value='0']").attr("selected", true);
                $("#selectOrderStatus").select2();
                $("#selectTravelNature option[value='0']").attr("selected", true);
                $("#selectTravelNature").select2();
            }
            if (data != null && data.Data != null) {
                var result = data.Data;
                bindGrabOrders(result.Items);
                loadPage(result.TotalPage);
                //控制是否展示定制师信息一列
                if (userType == 'VendorAdmin' && isAll) {
                    $('.js_platformUser').show();
                    $('.js_platformUserTd').show();
                } else {
                    $('.js_platformUser').hide();
                    $('.js_platformUserTd').hide();
                }

                if (userType == "AdminPlatformUser") {
                    $(".js_orderStatus").hide();
                }
                else {
                    $(".js_progress").hide();
                }

                //提示是否抢单
                $(".grabOrder").on("click", function () {
                    if ($(this).attr("disabled") == "disabled" || userType == "VendorAdmin" || userType == "AdminPlatformUser")
                        return;
                    var index = $(this).attr("data-index");
                    $("#waitingForGrabOrderTrIndex").val(index);
                    var requireDetailID = $("#requireDetailID_" + index).text();
                    $('#waitingForRequireDetailID').val(requireDetailID);
                    var platformUserID = $("#platformUserID_" + index).text();
                    $('#waitingForPlatformUserID').val(platformUserID);
                    var platformProviderID = $("#platformProviderID_" + index).text();
                    $('#waitingForPlatformProviderID').val(platformProviderID);
                    $("#waitingForRequireID").val($("#requireID_" + index).text());
                    $(".js_remindGrabOrder").show();
                });

                //关闭抢单提示框
                $(".js_close").on("click", function () {
                    $(".js_remindGrabOrder").hide();
                });

                //获取每个订单对应用户标签
                $.each(result.Items, function (o, i) {
                    //获取用户标签
                    getComputerUserTag(o, i.RequireDetailID);
                });
            }
            isloading = false;
        },
        null, {
            complete: function () {
                isloading = false;
                jQuery("#base_bd").closemask();
            }
        });
}

/*绑定数据到模板*/
function bindGrabOrders(data) {
    var html = jQuery('#grabOrderList_tpl').html();
    var template = _.template(html);
    var dom = template({
        "data": data
    });
    jQuery('#grabOrderList').html(dom);
}

function bindEvents() {
    $("#filterOrderId").blur(function () {
        var requireID = $("#filterOrderId").val();
        if (requireID == '') {
            $("#queryWarning").hide();
            return;
        }
        var patt = new RegExp(/^\d{10}$/);
        requireID = $.trim(requireID);
        if (!patt.test(requireID)) {
            $("#queryWarning").show();
        } else {
            $("#queryWarning").hide();
        }
    });
    //查询抢单信息
    $("#queryButton").on("click", function () {
        var requireID = $("#filterOrderId").val();
        var patt = new RegExp(/^\d{10}$/);
        requireID = $.trim(requireID);
        if (requireID != '' && !patt.test(requireID)) {
            $("#queryWarning").show();
            return;
        } else {
            $("#queryWarning").hide();
        }
        pageIndex = 1;
        loadOrderData("manualFilter");
    });
    //是否显示全部需求单
    $('#checkOrderCond').on("click", function (e) {
        isAll = $('#checkOrderCond').prop("checked");
        if (isloading == true) {
            alert('数据加载中，请稍后再试！');
            return;
        }
        pageIndex = 1;
        loadOrderData();
    });

    //切换状态
    $("#selectOrderStatus").bind("change", function () {
        pageIndex = 1;
        $("#filterOrderId").val('');
        loadOrderData("manualFilter");
    });

    $("#selectTravelNature").bind("change", function () {
        pageIndex = 1;
        $("#filterOrderId").val('');
        loadOrderData("manualFilter");
    });

    //抢单提示，确认抢单操作
    $(".confirmGrabOrder").on("click", function () {
        $(".js_remindGrabOrder").hide();
        var index = $("#waitingForGrabOrderTrIndex").val();
        var obj = $("tr_" + index);
        var requireDetailID = $('#waitingForRequireDetailID').val();
        var platformUserID = $('#waitingForPlatformUserID').val();
        var platformProviderID = $('#waitingForPlatformProviderID').val();
        var requireID = $('#waitingForRequireID').val();
        confirmGrabOrder(obj, requireDetailID, platformUserID, platformProviderID, requireID);
    });

    //关闭抢单失败提示框
    $(".js_grabFailClose").on("click", function () {
        $(".js_remindFailedGrabOrder").hide();
    });
}

/*生成随机数*/
function getRandom(n) {
    return Math.floor(Math.random() * n);
}

//获取用户标签信息
function getComputerUserTag(i, requireDetailID) {
    jQuery.ajax({
        url: '../GrabRequire/GetComputeUserTag',
        type: "post",
        data: {
            requireDetailID: requireDetailID
        },
        success: function (data) {
            if (data != null) {
                if (data.GradeLabel == '' && data.PriceSensitiveLabel == '' && data.GenerousLabel == '') {
                    $('#tag_' + i).text('无');
                } else {
                    if (data.PriceSensitiveLabel != '') $(".js_price_sensitive_i_" + i).text(data.PriceSensitiveLabel).show();
                    if (data.GradeLabel != '') $(".js_grade_i_" + i).text(data.GradeLabel).show();
                    if (data.GenerousLabel != '') $(".js_generous_i_" + i).text(data.GenerousLabel).show();
                }
            }
        }
    });
}

//获取供应商子账号下拉框信息
//function getPlatformUserListByProviderId(platformProviderID) {
//    jQuery.ajax({
//        url: '../GrabRequire/GetPlatformUserListByProviderID',
//        type: "post",
//        data: { platformProviderID: platformProviderID },
//        success: function (data) {
//            var optionHTML = '<option value=all>全部</option>';
//            if (data && data.length > 0) {
//                $.each(data, function (i, n) {
//                    optionHTML += '<option value="' + n.PlatformUserId + '">' + n.SubAccountName + '</option>';
//                })
//            }

//            $('#platformUser').html(optionHTML);
//        }
//    });
//}

//确认抢单
function confirmGrabOrder(obj, requireDetailId, platformUserId, platformProviderId, requireID) {
    var grabOrderTr = $(obj);
    if (grabOrderTr.attr("disabled") == "disabled" || userType == "VendorAdmin" || userType == "AdminPlatformUser")
        return;
    grabOrderTr.attr("disabled", true);

    verifyCode.para = {};
    verifyCode.para.requireDetailId = requireDetailId;
    verifyCode.para.platformUserId = platformUserId;
    verifyCode.para.platformProviderId = platformProviderId;
    verifyCode.para.requireID = requireID;


    verifyCode.currBtn = grabOrderTr;

    verifyCode.showVerifyCode();
    verifyCode.refresh();
    verifyCode.edition = "new";

    // doSubmit(grabOrderTr, requireDetailId, platformUserId, platformProviderId);
    return true;
}

//抢单操作
function doSubmit(grabOrderTr, requireDetailId, platformUserId, platformProviderId, verifyToken, jsVersion, requireID) {
    jQuery("#base_bd").openmask("数据通信请等待....");
    isSubmit = true;
    var paras = {
        requireDetailId: requireDetailId,
        platformUserId: platformUserId,
        platformProviderId: platformProviderId,
        orderType: "GrabOrder"
    };

    jQuery.ajax({
        url: '../GrabRequire/Submit',
        type: 'POST',
        data: {
            requireDetailId: requireDetailId,
            platformUserId: platformUserId,
            platformProviderId: platformProviderId,
            orderType: orderType,
            verifyToken: verifyToken,
            jsVersion: jsVersion
        },
        dataType: 'JSON',
        success: function (data) {
            if (data && data.Success) {
                verifyCode.hideVerifyCode();

                //判断是否在白名单里面
                $.ajax({
                    url: '../OrderProcess/GetIsGoVenderWeb',
                    type: 'POST',
                    dataType: 'json',
                    success: function (res) {
                        if (res) {
                            window.open('/ttl_vbk/ctrip_custom_system/?requireId=' + requireID + '&inquirySupplyId=' + data.Data.InquirySupplyID + '&inquiryId=' + data.Data.InquiryID, "_blank");
                        } else {
                            window.open('../OrderProcess/NewDetail?inquiryId=' + data.Data.InquiryID + '&inquirySupplyId=' + data.Data.InquirySupplyID + '&requireDetailId=' + requireDetailId + '&requireId=' + requireID + '&sourcefrom=contactMobile' + "&tab=orderBasicDetail", "_blank");
                        }
                    },
                    error: function (err) {
                        window.open('../OrderProcess/NewDetail?inquiryId=' + data.Data.InquiryID + '&inquirySupplyId=' + data.Data.InquirySupplyID + '&requireDetailId=' + requireDetailId + '&requireId=' + requireID + '&sourcefrom=contactMobile' + "&tab=orderBasicDetail", "_blank");

                    }
                });
                //window.open('../OrderProcess/NewDetail?inquiryId=' + data.Data.InquiryID + '&inquirySupplyId=' + data.Data.InquirySupplyID + '&requireDetailId=' + requireDetailId + '&requireId=' + requireID + '&sourcefrom=contactMobile' + "&tab=orderBasicDetail", "_blank");
                //$('.grabSuccess').fadeIn();
                //setTimeout(function () {
                //    $('.grabSuccess').fadeOut();
                //    loadOrderData();
                //}, 3000);
            } else if (data && !data.Success) {

                if (grabOrderTr) {
                    grabOrderTr.attr("disabled", false);
                }
                $(".js_grabOrderFailed").html(data.Message);
                //$('.grabFailed').fadeIn();
                //setTimeout(function () {
                //    $('.grabFailed').fadeOut();
                //    loadOrderData();

                //    if (data.IsVerifySuccess) {
                //        verifyCode.hideVerifyCode();
                //    } else {
                //        verifyCode.showVerifyCode();
                //        verifyCode.refresh();
                //    }


                //}, 3000);
                if (data.IsVerifySuccess) {
                    verifyCode.hideVerifyCode();
                } else {
                    verifyCode.showVerifyCode();
                    verifyCode.refresh();
                }
                $(".js_remindFailedGrabOrder").show();
            }

            isSubmit = false;
        },
        complete: function (XMLHttpRequest, textStatus) {
            isSubmit = false;
            jQuery("#base_bd").closemask();
        }
    })

}

function initalTable() {
    $('#example2').DataTable({
        "iDisplayLength": 10, //默认每页数量
        "paging": false,
        "lengthChange": false,
        "searching": false,
        "ordering": true,
        "info": false,
        "autoWidth": false,
        "aoColumns": [
            {"asSorting": [], "bSortable": false},
            {"asSorting": ["desc", "asc"]},
            {"asSorting": ["desc", "asc"]},
            {"asSorting": [], "bSortable": false},
            {"asSorting": [], "bSortable": false},
            {"asSorting": [], "bSortable": false},
            {"asSorting": [], "bSortable": false},
            {"asSorting": ["desc", "asc"]},
            {"asSorting": ["desc", "asc"]},
            {"asSorting": ["desc", "asc"]},
            {"asSorting": [], "bSortable": false},
            {"asSorting": [], "bSortable": false},
            {"asSorting": [], "bSortable": false},
            {"asSorting": ["asc", "desc"]}
        ]
    });
}

//初始化分页功能
function loadPage(totalPages) {
    if (totalPages <= 0) {
        $('#pageNation').hide();
        return;
    } else {
        $('#pageNation').show();
    }

    var options = {
        bootstrapMajorVersion: 2, //版本
        currentPage: pageIndex, //当前页数
        totalPages: totalPages, //总页数
        itemTexts: function (type, page, current) {
            switch (type) {
                case "first":
                    return "首页";
                case "prev":
                    return "上一页";
                case "next":
                    return "下一页";
                case "last":
                    return "末页";
                case "page":
                    return page;
            }
        },
        //点击事件，用于通过Ajax来刷新整个list列表
        onPageClicked: function (event, originalEvent, type, page) {
            pageIndex = page;
            loadOrderData();
        }
    };

    $('#pageNation').bootstrapPaginator(options);
}
